package com.LeetCode.Graph;


import org.junit.Test;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 课程表 Ⅱ 要求给出完成的序列
 */
public class FindCourseOrder {

    public int[] findOrder(int numCourses, int[][] prerequisites) {
        int[] res = new int[numCourses];
        int[] indegress = new int[numCourses];
        List<List<Integer>> graph = new ArrayList<>();
        Queue<Integer> queue = new LinkedList<>();

        for(int i = 0; i<numCourses; i++){
            graph.add(new ArrayList<>());
        }

        for(int[] tuple : prerequisites){
            indegress[tuple[0]]++;//入度++
            graph.get(tuple[1]).add(tuple[0]);//出度临接表
        }

        for(int i = 0; i<numCourses; i++){
            if(indegress[i] == 0)
                queue.offer(i);
        }

        int index = 0;

        while(!queue.isEmpty()){
            int preCourse = queue.poll();
            res[index++] = preCourse;

            for(int curCourse : graph.get(preCourse)){
                indegress[curCourse]--;
                if(indegress[curCourse] == 0) queue.offer(curCourse);
            }
        }

        return index == numCourses ? res : new int[0];
    }

    @Test
    public void test(){
        int[][] prerequisites1 = {
                {1,0},
                {2,0},
                {3,1},
                {3,2}
        };

        int[][] prerequisites2 = {
                {1,0},
                {0,1}
        };

        for(int num : findOrder(4,prerequisites1)){
            System.out.println(num);
        }
    }
}






















